package com.wbs.shop.nuby.view.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSONObject;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.wbs.shop.nuby.App;
import com.wbs.shop.nuby.R;
import com.wbs.shop.nuby.api.ApiHelper;
import com.wbs.shop.nuby.api.RxHelper;
import com.wbs.shop.nuby.api.RxSubscribe;
import com.wbs.shop.nuby.bean.TabEntity;
import com.wbs.shop.nuby.commom.Key;
import com.wbs.shop.nuby.utils.ActivityManger;
import com.wbs.shop.nuby.utils.FragmentChangeManager;
import com.wbs.shop.nuby.utils.Logger;
import com.wbs.shop.nuby.utils.NubyLocalBroadcastManager;
import com.wbs.shop.nuby.utils.ReflectUtil;
import com.wbs.shop.nuby.utils.Utils;
import com.wbs.shop.nuby.view.base.BaseActivity;
import com.wbs.shop.nuby.view.dialog.AlertDialog;
import com.wbs.shop.nuby.view.fragment.BaseWebViewFragmnet;
import com.wbs.shop.nuby.view.listener.OnReloadListener;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import java.util.ArrayList;

import butterknife.BindView;
import me.jessyan.autosize.utils.AutoSizeUtils;

public class MainActivity extends BaseActivity implements OnTabSelectListener, OnReloadListener {
    @BindView(R.id.tl_nav)
    CommonTabLayout nav;
    private FragmentChangeManager mFragmentChangeManager;
    ArrayList<Fragment> fragments;
    ArrayList<CustomTabEntity> customTabEntities;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setFormat(PixelFormat.TRANSLUCENT);//（这个对宿主没什么影响，建议声明）
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        if (hasExtras())
            openUrl(getIntent().getExtras().getString(Key.OPEN_URL));
        nav.setTabData(customTabEntities);
        nav.setOnTabSelectListener(this);
        handIconSize();
        if (savedInstanceState != null) {
            onTabSelect(savedInstanceState.getInt(Key.MAIN_TAB_INDEX));
        } else {
            onTabSelect(0);
        }
        initBroadcastReceiver();
        chechUpdate();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null && intent.getExtras() != null && intent.getExtras().containsKey(Key.SID)) {
            NubyLocalBroadcastManager.sendChangSidBroadcastSync(intent.getStringExtra(Key.SID), intent.getStringExtra(Key.AID));
            openUrl(intent.getStringExtra(Key.OPEN_URL));
        }
    }

    private void openUrl(String openUrl) {
        if (!TextUtils.isEmpty(openUrl)) {
            Bundle bundle = new Bundle();
            bundle.putString(Key.URL, openUrl);
            goActicity(WebViewActivity.class, bundle);
        }
    }

    private void init() {
        fragments = new ArrayList<>();
        String[] urlArr = {"%s/shop.html", "%s/product_list.html", "%s/cart.html", "%s/me.html"};
        BaseWebViewFragmnet fragment;
        Bundle bundle;
        for (int i = 0; i < urlArr.length; i++) {
            fragment = new BaseWebViewFragmnet();
            bundle = new Bundle();
            bundle.putString(Key.URL, String.format(urlArr[i], ApiHelper.getHost()));
            bundle.putString(Key.SID, getIntent().getStringExtra(Key.SID));
            bundle.putString(Key.AID, getIntent().getStringExtra(Key.AID));
            if (i > 1)
                bundle.putBoolean(Key.IS_BROADCAST_RECEIVER, true);
            fragment.setArguments(bundle);
            fragments.add(fragment);
        }
        mFragmentChangeManager = new FragmentChangeManager(getSupportFragmentManager(), R.id.frameLayout, fragments);

        customTabEntities = new ArrayList<>();
        customTabEntities.add(new TabEntity(getString(R.string.text_home), R.mipmap.tool_home, R.mipmap.tool_home_click));
        customTabEntities.add(new TabEntity(getString(R.string.text_goods), R.mipmap.tool_goods, R.mipmap.tool_goods_click));
        customTabEntities.add(new TabEntity(getString(R.string.text_cart), R.mipmap.tool_cart, R.mipmap.tool_cart_click));
        customTabEntities.add(new TabEntity(getString(R.string.text_my), R.mipmap.tool_my, R.mipmap.tool_my_clisk));
    }

    @Override
    public void onTabSelect(int position) {
        mFragmentChangeManager.setFragments(position);
    }

    @Override
    public void onTabReselect(int position) {
//        ((BaseWebViewFragmnet) fragments.get(position)).reload();
    }

    public void refreshWebViewFragmnet(int position) {
        try {
            ((BaseWebViewFragmnet) fragments.get(position)).reload();
        } catch (Exception e) {

        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        if (nav != null) {
            outState.putInt(Key.MAIN_TAB_INDEX, nav.getCurrentTab());
        }
        super.onSaveInstanceState(outState);
    }

    private void handIconSize() {
        try {
            LinearLayout mTabsContainer = ReflectUtil.getFiledValue(nav, "mTabsContainer");
            if (mTabsContainer != null)
                for (int i = 0; i < customTabEntities.size(); i++) {
                    View tabView = mTabsContainer.getChildAt(i);
                    View view = tabView.findViewById(R.id.iv_tab_icon);
                    ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
                    int width = AutoSizeUtils.dp2px(this, 22);
                    ;
                    if (layoutParams == null) {
                        layoutParams = new LinearLayout.LayoutParams(width, width);
                    } else {
                        layoutParams.width = width;
                        layoutParams.height = width;
                    }
                    view.setLayoutParams(layoutParams);
                }
        } catch (Exception e) {
            Logger.e(e);
        }
    }

    private void initBroadcastReceiver() {
        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Logger.e("BroadcastReceiver==>" + intent.getAction());
                if (Key.ACTION_INDEX_CHANG.equals(intent.getAction())) {
                    int index = intent.getIntExtra(Key.KEY_INDEX, 0);
//                    String goUrl = intent.getStringExtra(Key.KEY_GO_URL);
                    boolean refresh = intent.getBooleanExtra(Key.KEY_REFRESH, false);
                    nav.setCurrentTab(index);
                    onTabSelect(index);
                    if (refresh) {
                        refreshWebViewFragmnet(index);
                    }
                } else if (Key.ACTION_INDEX_SID_CHANG.equals(intent.getAction())) {
                    for (Fragment fragmnet : fragments) {
                        if (fragmnet instanceof BaseWebViewFragmnet)
                            ((BaseWebViewFragmnet) fragmnet).changSid(intent.getStringExtra(Key.SID), intent.getStringExtra(Key.AID));
                    }
                }
            }
        };
        NubyLocalBroadcastManager.registerMainReceiver(mBroadcastReceiver);
    }

    @Override
    public void onReload() {
        refreshWebViewFragmnet(mFragmentChangeManager.getCurrentTab());
    }

    //退出时的时间
    private long mExitTime;

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Utils.toastMessageLong("再按一次退出");
            mExitTime = System.currentTimeMillis();
        } else {
            App.getApp().exit();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (event.getRepeatCount() == 0) {
                exit();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void chechUpdate() {
        ApiHelper.getApiService().version()
                .compose(RxHelper.handleResult(this))
                .subscribe(new RxSubscribe<JSONObject>() {
                    @Override
                    protected void _onNext(JSONObject jsonObject) {
                        AndPermission.with(MainActivity.this)
                                .runtime()
                                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                                .onDenied(data -> handUpdate(jsonObject))
                                .onGranted(data -> handUpdate(jsonObject))
                                .start();

                    }
                });
    }

    private void handUpdate(JSONObject jsonObject) {
        String apkUrl = jsonObject.getString("apkUrl");
//                        boolean isForce = jsonObject.getBoolean("isForce");
        boolean isForce = true;
        if (Utils.isUpdate(getApplicationContext(), jsonObject.getString("versionName"))) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this)
                    .setMessage(jsonObject.getString("changeLog"));
            if (!isForce)
                builder.setNegativeButton(R.string.button_cancel, null);
            builder.setPositiveButton(R.string.button_update, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityManger.getCurActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(apkUrl)));
                }
            })
                    .setCancelable(!isForce)
                    .create()
                    .show();
        }
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
//            webview.goBack();
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }
}
